package logics

import (
	"backenddev/shop_server/internal/defs"
	"backenddev/shop_server/internal/models"
	"backenddev/shop_server/pkg/mysqldb"
	"backenddev/shop_server/pkg/redisdb"
	reqs "backenddev/shop_server/requests"
	"time"
)

// 获取热门的商品
// 先去Redis中取，没有则去数据库中取
func GetHotProduct() ([]*models.Product, error) {
	products := []*models.Product{}
	//先去Redis中取
	err := redisdb.RedisDb.Get(redisdb.RedisCtx, defs.Hot_products).Scan(&products)
	if err == nil {
		return products, nil
	}
	product := &models.Product{}
	result := mysqldb.Mysql.Table(product.TableName()).Where("IsOnSale = ?", 1).Order("view_count desc").Limit(defs.Hot_products_num).Find(&products)
	//存到Redis中
	redisdb.RedisDb.Set(redisdb.RedisCtx, defs.Hot_products, products, time.Hour*24)
	return products, result.Error
}

// 添加商品
func AddProduct(req *reqs.AddProductReq) (int64, error) {
	product := &models.Product{}
	product.Name = req.Name
	product.CategoryId = req.CategoryId
	product.Sku = req.Sku
	product.Price = req.Price
	product.Stock = req.Stock
	product.IsOnSale = req.IsOnSale
	product.Description = req.Description

	result := mysqldb.Mysql.Create(product)
	return product.Id, result.Error
}
